import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { Input, Button, Avatar } from "antd";
import axios from "axios";

const { TextArea } = Input;

// 当前登录用户ID（你可以从登录状态中动态获取）
const CURRENT_USER_ID = 76;

const ConversationView = () => {
  const { userId } = useParams();
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState("");

  useEffect(() => {
    axios
      .get(
        `http://127.0.0.1:4523/m1/6367429-6063635-973503d5/messages/conversation/13`
      )
      .then((res) => {
        setMessages(res.data.data.records);
      });
  }, [userId]);

  const handleSend = () => {
    if (!input.trim()) return;
    const newMsg = {
      senderId: CURRENT_USER_ID,
      content: input,
      avatar: "https://api.dicebear.com/7.x/bottts-neutral/svg?seed=Me",
    };
    setMessages((prev) => [...prev, newMsg]);
    setInput("");
    // axios.post(`/api/conversation/${userId}`, { content: input });
  };

  return (
    <div style={{ padding: 24, maxWidth: 600, margin: "0 auto" }}>
      <h2>与用户 {userId} 的对话</h2>
      <div
        style={{
          height: "60vh",
          overflowY: "auto",
          border: "1px solid #eee",
          padding: 12,
          marginBottom: 16,
          backgroundColor: "#f9f9f9",
        }}
      >
        {messages.map((msg, idx) => {
          const isSelf = msg.senderId === CURRENT_USER_ID;
          return (
            <div
              key={idx}
              style={{
                display: "flex",
                justifyContent: isSelf ? "flex-end" : "flex-start",
                marginBottom: 12,
              }}
            >
              {!isSelf && (
                <Avatar style={{ marginRight: 8 }} src={msg.avatar} />
              )}
              <div
                style={{
                  backgroundColor: isSelf ? "#95ec69" : "#fff",
                  color: "#000",
                  padding: "8px 12px",
                  borderRadius: 16,
                  maxWidth: "60%",
                  boxShadow: "0 1px 2px rgba(0,0,0,0.1)",
                }}
              >
                {msg.content}
              </div>
              {isSelf && <Avatar style={{ marginLeft: 8 }} src={msg.avatar} />}
            </div>
          );
        })}
      </div>

      <TextArea
        rows={3}
        value={input}
        onChange={(e) => setInput(e.target.value)}
        placeholder="输入消息..."
      />
      <Button type="primary" onClick={handleSend} style={{ marginTop: 8 }}>
        发送
      </Button>
    </div>
  );
};

export default ConversationView;
